import pymysql
import traceback
class DB:
    def __init__(self,user,password,host,database):
        self.user = user
        self.password = password
        self.host = host
        self.database = database
    def connect(self):
        # 创建数据库对象
        self.db = pymysql.connect(host = self.host,user = self.user,password = self.password,database = self.database,cursorclass =
        pymysql.cursors.DictCursor)
        # 创建游标
        self.cursor = self.db.cursor()
    def close(self):
        self.cursor.close()
        self.db.close()
    def searchOne(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchone()
            return result
        except:
            self.db.rollback()
            traceback.print_exc()
            return result
        finally:
            self.close()

    def searchAll(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchall()
            return result
        except:
            self.db.rollback()
            traceback.print_exc()
            return result
        finally:
            self.close()

    def __edit(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            self.db.commit()
            result = 1
            return result
        except:
            self.db.rollback()
            traceback.print_exc()
            return result
        finally:
            self.close()

    def insert(self,sql):
        return self.__edit(sql)

    def delete(self,sql):
        return self.__edit(sql)

    def update(self,sql):
        return self.__edit(sql)
"""
if __name__ == '__main__':
    # 实例化数据库对象
    d1 = DB(user='root',password='1965331442Xby@',host='47.99.105.120',database='crmeb')
    # 查询
    print(d1.searchAll('select * from eb_user_group'))
"""
